/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, " ") +
      '"}'
  );
}
/**
 * delete null Array
 * @param {Array} arr
 * @returns {Object}
 * @author zj
 */
export function removeNullArray(arr) {
  if (arr.length) {
    arr.forEach((child) => {
      // judge whether there are particular attribute in child
      if (Object.prototype.hasOwnProperty.call(child, "children")) {
        if (!child.children.length) {
          delete child["children"];
        } else {
          removeNullArray(child.children);
        }
      }
    });
  } else {
    throw Error("Expected non-null Array, got null");
  }
}

/**
 * data formatter
 * @param { String-timestamp } daterc
 * @returns { String }
 * @author zj
 */
export function dateFormat(daterc) {
  if (!daterc) {
    return "";
  }
  const dateMat = new Date(daterc);
  const year = dateMat.getFullYear();
  const month = dateMat.getMonth() + 1;
  const day = dateMat.getDate();
  let hh = dateMat.getHours();
  let mm = dateMat.getMinutes();
  let ss = dateMat.getSeconds();
  hh = hh > 9 ? hh : "0" + hh;
  mm = mm > 9 ? mm : "0" + mm;
  ss = ss > 9 ? ss : "0" + ss;
  const timeFormat =
    year + "/" + month + "/" + day + " " + hh + ":" + mm + ":" + ss;
  return timeFormat;
}

/**
 * second formatter
 * @param { String-timestamp } daterc
 * @returns { String }
 * @author zj
 */
export function secondFormat(daterc) {
  if (!daterc) {
    return "";
  }
  const dateMat = new Date(daterc);
  let hh = dateMat.getHours();
  let mm = dateMat.getMinutes();
  let ss = dateMat.getSeconds();
  hh = hh > 9 ? hh : "0" + hh;
  mm = mm > 9 ? mm : "0" + mm;
  ss = ss > 9 ? ss : "0" + ss;
  const timeFormat = hh + ":" + mm + ":" + ss;
  return timeFormat;
}

export function dayFormat(daterc) {
  if (!daterc) {
    return "";
  }
  let dateMat = daterc;
  if (daterc.constructor !== Date) {
    dateMat = new Date(daterc);
  }
  const year = dateMat.getFullYear();
  const month = dateMat.getMonth() + 1;
  const day = dateMat.getDate();
  const timeFormat = year + "-" + month + "-" + day;
  return timeFormat;
}
/**
 * get parent by parentId
 * @param {Array} data  full data result returned by search
 * @param {Number} id parentId
 * @param {Object} rlt result
 * @author zj
 */
export function getParentById(data, id, rlt) {
  if (Array.isArray(data)) {
    data.forEach((item) => {
      if (item.id == id) {
        Object.assign(rlt, item);
      } else {
        getParentById(item.children, id, rlt);
      }
    });
  } else {
    throw Error("Expected Array, got else");
  }
}

export function getOrgById(orgs, id, rlt) {
  for (let item of orgs) {
    if (item.id == id) {
      rlt.push(item);
    } else if (item.children) {
      getOrgById(item.children, id, rlt);
    }
  }
}

export function searchOrgName(arr, fn, result, id) {
  try {
    arr.forEach((item) => {
      if (item.id != id) {
        searchOrgName(item.children, fn, result, id);
      } else {
        if (fn(item)) {
          result.push(item.text);
          throw new Error("exit");
        }
      }
    });
  } catch (e) {
    //
  }
}

/**
 * download files via relative uri from mips project server
 * @param {String} fileUriParam  relative uri   eg: files/download?fileIds=9527,
 * @author zj
 */
export function downloadMips(fileUriParam) {
  if (typeof fileUriParam !== "string") {
    throw Error("excepted String, got others");
  }

  if (!fileUriParam) {
    throw Error("excepted NotNull, got Null");
  }

  const fileUri = fileUriParam.startsWith("/")
    ? fileUriParam.slice(1)
    : fileUriParam; // if first character '/', remove it
  let a = document.createElement("a");
  a.setAttribute("download", "");
  a.href = "/playControlApi/" + fileUri;
  a.click(fileUriParam);
}
//设备导出
export function deviceExportA(fileUriParam, select) {
  if (typeof fileUriParam !== "string") {
    throw Error("excepted String, got others");
  }

  if (!fileUriParam) {
    throw Error("excepted NotNull, got Null");
  }
  // deviceType
  //根据语言环境导出
  let langStr = "";
  if (localStorage.getItem("lang") == "en") {
    langStr = "en_US";
  } else {
    langStr = "zh_CN";
  }
  let fileUrii = fileUriParam.startsWith("/")
    ? fileUriParam.slice(1)
    : fileUriParam; // if first character '/', remove it
  fileUrii =
    fileUrii +
    "?" +
    "orgId=" +
    select.orgId +
    "&deviceName=" +
    select.deviceName +
    "&deviceIp=" +
    select.deviceIp +
    "&orientation=" +
    select.orientation +
    "&containSub=" +
    select.containSub +
    "&deviceType=" +
    select.deviceType +
    "&isAudit=" +
    select.isAudit +
    "&deviceTypeDetail=" +
    select.deviceTypeDetail +
    "&online=" +
    select.online +
    "&lang=" +
    langStr;
  let a = document.createElement("a");
  a.setAttribute("download", "");
  a.href = "/playControlApi/" + fileUrii;
  a.click();
}
/**
 * change num to bytes
 * @param { Number } limit  file size
 * @author download form csdn blog
 */
export function changeNum2Size(limit) {
  var size = "";
  if (limit < 0.1 * 1024) {
    //小于0.1KB，则转化成B
    size = limit.toFixed(2) + "B";
  } else if (limit < 0.1 * 1024 * 1024) {
    //小于0.1MB，则转化成KB
    size = (limit / 1024).toFixed(2) + "KB";
  } else if (limit < 0.1 * 1024 * 1024 * 1024) {
    //小于0.1GB，则转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + "MB";
  } else {
    //其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
  }

  var sizeStr = size + ""; //转成字符串
  var index = sizeStr.indexOf("."); //获取小数点处的索引
  var dou = sizeStr.substr(index + 1, 2); //获取小数点后两位的值
  if (dou == "00") {
    //判断后两位是否为00，如果是则删除00
    return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);
  }
  return size;
}

/*****************************************************************
 * 函数名: trim
 * 功能: 去空格
 * 参数:
 * 返回值:
 * Author: csp
 ******************************************************************/
export function trim(str) {
  return str.replace(/(^\s*)|(\s*$)/g, "");
}

/*****************************************************************
 * 函数名: systemType
 * 功能: 重写console方法
 * 参数:
 * 返回值:
 * Author: csp
 ******************************************************************/
export function rewriteConsole() {
  let console = {};
  console.log = function() {};
  console.info = function() {};
  console.error = function() {};
  window.console = console;
}
/*****************************************************************
 * 函数名: findComponentUpward
 * 功能: 向上查找查找指定的组件
 * 参数: context：当前组件的this,
 * 		componentName:查找目标组件的name
 * 返回值: 组件的this
 * Author: csp
 ******************************************************************/
export function findComponentUpward(context, componentName, componentNames) {
  if (typeof componentName === "string") {
    componentNames = [componentName];
  } else {
    componentNames = componentName;
  }
  let parent = context.$parent;
  let name = parent.$options.name;
  while (parent && (!name || componentNames.indexOf(name) < 0)) {
    parent = parent.$parent;
    if (parent) name = parent.$options.name;
  }
  return parent;
}
/*****************************************************************
 * 函数名: findComponentDownward
 * 功能: 向下查找查找指定的组件
 * 参数: context：当前组件的this,
 * 		componentName:查找目标组件的name
 * 返回值: 组件的this
 * Author: csp
 ******************************************************************/
export function findComponentDownward(context, componentName) {
  const childrens = context.$children;
  let children = null;
  if (childrens.length) {
    for (const child of childrens) {
      const name = child.$options.name;
      if (name === componentName) {
        children = child;
        break;
      } else {
        children = findComponentDownward(child, componentName);
        if (children) break;
      }
    }
  }
  return children;
}
/*****************************************************************
 * 函数名: findComponentsDownward
 * 功能: 向下查找所有指定的组件
 * 参数: context：当前组件的this,
 * 		componentName:查找目标组件的name
 * 返回值: 所有符合的组件数组
 * Author: csp
 ******************************************************************/
export function findComponentsDownward(context, componentName) {
  return context.$children.reduce((components, child) => {
    if (child.$options.name === componentName) components.push(child);
    const foundChilds = findComponentsDownward(child, componentName);
    return components.concat(foundChilds);
  }, []);
}

/*****************************************************************
 * 函数名: findBrothersComponents
 * 功能: 查找兄弟指定的组件
 * 参数: context：当前组件的this,
 * 		componentName:查找目标组件的name,
 * 		exceptMe是否包含自己
 * 返回值: 组件的this
 * Author: csp
 ******************************************************************/
export function findBrothersComponents(
  context,
  componentName,
  exceptMe = true
) {
  let res = context.$parent.$children.filter((item) => {
    return item.$options.name === componentName;
  });
  let index = res.findIndex((item) => item._uid === context._uid);
  if (exceptMe) res.splice(index, 1);
  return res;
}
/******************************************************************
 * 函数名: getLocalStorage
 * 功能: 获取本地存储数据
 * 参数: key(String)指定的键
 * 返回值: 转换后的对象
 * Author: csp
 * 修改日期：2019/10/22
 ******************************************************************/
export function getLocalStorage(key) {
  return JSON.parse(localStorage.getItem(key));
}
/******************************************************************
 * 函数名: setLocalStorage
 * 功能: 设置本地存储数据
 * 参数: key(String)键，
 *  value(Object|String)值
 * 返回值: 无
 * Author: csp
 ******************************************************************/
export function setLocalStorage(key, value) {
  localStorage.setItem(key, JSON.stringify(value));
}
/*****************************************************************
 * 函数名: removeLocalStorage
 * 功能: 清除本地存储数据
 * 参数: key(String)键
 * 返回值: 无
 * Author: csp
 ******************************************************************/
export function removeLocalStorage(key) {
  localStorage.removeItem(key);
}
/*****************************************************************
 * 函数名: localToSelect
 * 功能: 把缓存数据转换成select组件数据
 * 参数: key(String)键
 * 返回值: 无
 * Author: csp
 ******************************************************************/
export function localToSelect(data, type) {
  let selectObj = [];
  if (type == "orgList") {
    data.forEach((item) => {
      let obj = {
        value: item.orgId,
        label: item.orgName,
      };
      selectObj.push(obj);
    });
  } else if (type == "areaList") {
    data.forEach((item) => {
      let obj = {
        value: item.areaId,
        label: item.areaName,
      };
      selectObj.push(obj);
    });
  } else if (type == "deviceList") {
    data.forEach((item) => {
      let obj = {
        value: item.equipmentTypeId,
        label: item.typeName,
      };
      selectObj.push(obj);
    });
  } else if (type == "factoryList") {
    data.forEach((item) => {
      let obj = {
        value: item.manufacturerId,
        label: item.manufacturerName,
      };
      selectObj.push(obj);
    });
  }
  return selectObj;
}
/*****************************************************************
 * 函数名: confirmFn
 * 功能: 询问框
 * 参数: key(String)键
 * 返回值: 无
 * Author: csp
 ******************************************************************/
export function confirmFn(vm, text, fn) {
  vm.$confirm(text, "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    fn();
  });
}
/*****************************************************************
 * 函数名: cerrorEessageFn
 * 功能: 错误提示信息
 * 参数: key(String)键
 * 返回值: 无
 * Author: csp
 ******************************************************************/
export function cerrorEessageFn(vm, text, fn) {
  vm.$message({
    showClose: true,
    message: text,
    type: "error",
  });
  if (fn) {
    setTimeout(() => {
      fn();
    }, 2500);
  }
}
/*****************************************************************
 * 函数名: successEessageFn
 * 功能: 成功提示信息
 * 参数: key(String)键
 * 返回值: 无
 * Author: csp
 ******************************************************************/
export function successEessageFn(vm, text, fn) {
  vm.$message({
    showClose: true,
    message: text,
    type: "success",
  });
  if (fn) {
    setTimeout(() => {
      fn();
    }, 2500);
  }
}
